package logic

import (
	"context"
	"encoding/json"
	"fresh-box/cache"
	"fresh-box/hemarpc/hemarpc"
	"fresh-box/hemarpc/internal/svc"
	"fresh-box/models"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *hemarpc.ListRequest) (*hemarpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var freshs []models.FreshClass
	key := "freshList"
	cachejson, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cachejson == "" {
		models.DB.
			Table("freshes").
			Select("freshes.*",
				"classes.name as ClassName").
			Joins("left join classes on freshes.class_id=classes.id").
			Find(&freshs)
		cachedata, _ := json.Marshal(freshs)
		cache.Rdb.Set(cache.Ctx, key, cachedata, time.Minute*30)
	} else {
		json.Unmarshal([]byte(cachejson), &freshs)
	}
	var freshLists []*hemarpc.List
	for _, fresh := range freshs {
		list := hemarpc.List{
			Id:        int64(fresh.ID),
			Name:      fresh.Name,
			Title:     fresh.Title,
			Price:     float32(fresh.Price),
			Num:       int64(fresh.Num),
			ClassName: fresh.ClassName,
			FreshId:   int64(fresh.ID),
		}
		freshLists = append(freshLists, &list)
	}
	return &hemarpc.ListResponse{
		List: freshLists,
	}, nil
}
